package com.hlg.xboot.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.hlg.xboot.constants.AppConstants;
import com.hlg.xboot.enums.LogType;
import com.hlg.xboot.model.modules.User;
import com.hlg.xboot.model.sys.SysLog;
import com.hlg.xboot.model.sys.SysUser;
import com.digi_zones.common.utils.CommonUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 日志拦截器
 * @author yangxin
 */
@Component
public class LogInterceptor implements HandlerInterceptor {

    //@Autowired
   // private SysLogService logService;

    private Long beginTime;// 1、开始时间
    private Long endTime;// 2、结束时间

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        beginTime = System.currentTimeMillis();//计时
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        endTime = System.currentTimeMillis();
        String requestRri = request.getRequestURI();
        String uriPrefix = request.getContextPath();
        String operationCode = StringUtils.substringAfter(requestRri, uriPrefix);    //操作编码

        String requestParam = JSON.toJSONString(request.getParameterMap());          //请求参数

        Long executeTime = endTime - beginTime;
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader(HttpHeaders.USER_AGENT));
        String os = userAgent.getOperatingSystem().getName();    //获取客户端操作系统
        String browser = userAgent.getBrowser().getName();    //获取客户端浏览器

        SysLog log = new SysLog();
        log.setOs(os);
        log.setBrowser(browser);
        log.setIp(CommonUtils.getClientIPAddress(request));
        log.setOperationCode(operationCode);
        log.setExecuteTime(Integer.valueOf(executeTime.toString()));
        Object user = request.getSession().getAttribute(AppConstants.SESSION_USER);
        String userName;
        if (user instanceof User) {
            userName = ((User) user).getNickname();
        } else {
            userName = ((SysUser)user).getUsername();
        }
        log.setCreater(userName);
        log.setRequestParam(requestParam);
        log.setReferer(request.getHeader(HttpHeaders.REFERER));
        log.setType(LogType.API.getDesc());
        //logService.addLog(log);
    }

}
